import { useFormik } from "formik";
import * as Yup from "yup";

function App() {
  const formik = useFormik({
    initialValues: { username: "zh", password: "123456" },
    // validate: values => {
    //   const errors = {}
    //   if (!values.username) {
    //     errors.username = "请输入用户名"
    //   } else if (values.username.length > 15) {
    //     errors.username = "用户名的长度不能大于15"
    //   }
    //   if (!values.password) {
    //     errors.password = "请输入密码"
    //   }
    //   return errors
    // },

    // 使用yup进行表单验证
    validationSchema: Yup.object({
      username: Yup.string()
        .max(15, "用户名的长度不能大于15")
        .required("请填写用户名"),
      password: Yup.string()
        .min(6, "密码的长度不能小于6")
        .required("请填写密码"),
    }),
    onSubmit: (values) => {
      console.log(values);
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      {/* <input
        type="text"
        name="username"
        value={formik.values.username}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
      /> */}
      {/* 使用getFieldProps方法简化表单代码 */}
      <input
        type="text"
        name="username"
        {...formik.getFieldProps('username')}
      />
      <p>
        {formik.touched.username && formik.errors.username
          ? formik.errors.username
          : null}
      </p>
      {/* <input
        type="password"
        name="password"
        value={formik.values.password}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
      /> */}
      {/* 使用getFieldProps方法简化表单代码 */}
      <input
        type="password"
        name="password"
        {...formik.getFieldProps('password')}
      />
      <p>
        {formik.touched.password && formik.errors.password
          ? formik.errors.password
          : null}
      </p>
      <input type="submit" />
    </form>
  );
}

export default App;
